package com.sd.projectinterface;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.*;

/*
 * status = 0 means current game
 * status = 1 means previous game
 */

@SuppressLint({ "ParserError", "ParserError" })
public class MyGames extends Activity{
	
	Button current, past, back;
	//public static final String KEY_120 = "http://10.0.2.2/mathRomp/findPastGames.php";
	//public static final String KEY_121 = "http://10.0.2.2/mathRomp/findCurrentGames.php";
	public static final String KEY_120 = "http://10.0.2.2/mathRomp/findTheirTurnGames.php";
	public static final String KEY_121 = "http://10.0.2.2/mathRomp/findYourTurnGames.php";
	public static final String KEY_122 = "http://10.0.2.2/mathRomp/getTurn.php";
	int id;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_games);
		
		MyApplication myApp = (MyApplication) getApplicationContext();
        id = myApp.getId();
		
		LinearLayout container = (LinearLayout) findViewById(R.id.myGamesButtons);
		container.setVerticalScrollBarEnabled(true);
		
		JSONArray current = getCurrentGames();
		if(current != null){
			if(current.length() > 0){
				TextView curr =  new TextView(this);
				curr.setText("Your Turn:");
				container.addView(curr);
			}
			
			Button[] currentBtns = new Button[current.length()];
			
			for(int i=0; i<currentBtns.length; i++){
				currentBtns[i] = new Button(this);
				String u = "not working";
				try {
					JSONObject json_data = current.getJSONObject(i);
					u = json_data.getString("username");
					final int g = json_data.getInt("gameId");
					final int c = json_data.getInt("userId");
					currentBtns[i].setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							Intent i;
							if(id == getTurn(g)){
								i = new Intent(MyGames.this, ProblemView.class);
							}else{
								i = new Intent(MyGames.this, GameStats.class);
							}
							//Intent i = new Intent(MyGames.this, GameStats.class);
							
							//i.putExtra("userId", id);
							i.putExtra("gameId", g);
							i.putExtra("competitorId", c);
							startActivity(i);
						}
					});
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
				currentBtns[i].setText("Game with "+u);
				container.addView(currentBtns[i]);
			}
		}
		
		JSONArray past = getPastGames();
		if(past != null){
			if(past.length() > 0){
				TextView pst =  new TextView(this);
				pst.setText("Their Turn:");
				container.addView(pst);
			}
			
			Button[] pastBtns = new Button[past.length()];
			
			for(int i=0; i<pastBtns.length; i++){
				pastBtns[i] = new Button(this);
				String u = "not working";
				try {
					JSONObject json_data = past.getJSONObject(i);
					u = json_data.getString("username");
					final int g = json_data.getInt("gameId");
					final int c = json_data.getInt("userId");
					pastBtns[i].setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							Intent i = new Intent(MyGames.this, GameStats.class);
							//i.putExtra("userId", id);
							i.putExtra("gameId", g);
							i.putExtra("competitorId", c);
							startActivity(i);
						}
					});
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
				pastBtns[i].setText("Game with "+u);
				container.addView(pastBtns[i]);
			}
		}
		
		if(current!=null && past!=null){
			if((current.length() > 0) || (past.length() > 0)){
				TextView space =  new TextView(this);
				space.setText("");
				container.addView(space);
			}
		}
		
		back = (Button) findViewById(R.id.back);
		back.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(MyGames.this, MainActivity.class);
				i.putExtra("j", id);
				startActivity(i);
			}
		});
	}
	
	public JSONArray getCurrentGames(){
    	InputStream is = null;
    	String result = "";
    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    	nameValuePairs.add(new BasicNameValuePair("userId", id+""));
    	
    	//http post
    	try{
    		HttpClient httpclient = new DefaultHttpClient();
    		HttpPost httppost = new HttpPost(KEY_121);
    		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    		HttpResponse response = httpclient.execute(httppost);
    		HttpEntity entity = response.getEntity();
    		is = entity.getContent();
    	}catch(Exception e){
    		Log.e("log_tag", "Error in http connection: "+e);
    		return null;
    	}
    	
    	//convert response to string
    	try{
    		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
    		StringBuilder sb = new StringBuilder();
    		String line = null;
    		while((line = reader.readLine()) != null){
    			sb.append(line + "\n");
    		}
    		is.close();
    		result = sb.toString();
    		System.out.println(result);
    	}catch(Exception e){
    		Log.e("log_tag", "Error converting result: "+e);
    		return null;
    	}
    	
    	//parse json data
    	JSONArray jArray = null;
    	try{
    		jArray = new JSONArray(result);
    	}catch(JSONException e){
    		Log.e("log_tag", "Error parsing data: "+e);
    		return null;
    	}
    	return jArray;
    }
	
	public JSONArray getPastGames(){
    	InputStream is = null;
    	String result = "";
    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    	nameValuePairs.add(new BasicNameValuePair("userId", id+""));
    	
    	//http post
    	try{
    		HttpClient httpclient = new DefaultHttpClient();
    		HttpPost httppost = new HttpPost(KEY_120);
    		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    		HttpResponse response = httpclient.execute(httppost);
    		HttpEntity entity = response.getEntity();
    		is = entity.getContent();
    	}catch(Exception e){
    		Log.e("log_tag", "Error in http connection: "+e);
    		return null;
    	}
    	
    	//convert response to string
    	try{
    		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
    		StringBuilder sb = new StringBuilder();
    		String line = null;
    		while((line = reader.readLine()) != null){
    			sb.append(line + "\n");
    		}
    		is.close();
    		result = sb.toString();
    		System.out.println(result);
    	}catch(Exception e){
    		Log.e("log_tag", "Error converting result: "+e);
    		return null;
    	}
    	
    	//parse json data
    	JSONArray jArray = null;
    	try{
    		jArray = new JSONArray(result);
    	}catch(JSONException e){
    		Log.e("log_tag", "Error parsing data: "+e);
    		return null;
    	}
    	return jArray;
    }
	
	public int getTurn(int gameId){
    	InputStream is = null;
    	String result = "";
    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    	nameValuePairs.add(new BasicNameValuePair("gameId", gameId+""));
    	
    	//http post
    	try{
    		HttpClient httpclient = new DefaultHttpClient();
    		HttpPost httppost = new HttpPost(KEY_122);
    		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    		HttpResponse response = httpclient.execute(httppost);
    		HttpEntity entity = response.getEntity();
    		is = entity.getContent();
    	}catch(Exception e){
    		Log.e("log_tag", "Error in http connection: "+e);
    		return -1;
    	}
    	
    	//convert response to string
    	try{
    		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
    		StringBuilder sb = new StringBuilder();
    		String line = null;
    		while((line = reader.readLine()) != null){
    			sb.append(line + "\n");
    		}
    		is.close();
    		result = sb.toString();
    		System.out.println(result);
    	}catch(Exception e){
    		Log.e("log_tag", "Error converting result: "+e);
    		return -1;
    	}
    	
    	//parse json data
    	JSONArray jArray = null;
    	JSONObject jObject = null;
    	int turn = -1;
    	try{
    		jArray = new JSONArray(result);
    		jObject = jArray.getJSONObject(0);
    		turn = jObject.getInt("turn");
    		System.out.println("turn: "+turn);
    	}catch(JSONException e){
    		Log.e("log_tag", "Error parsing data: "+e);
    		return -1;
    	}
    	return turn;
    }
}
